﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RedemptoristRetreatCenter.DatabaseUtility;
using RedemptoristRetreatCenter.HelperUtility;

namespace RedemptoristRetreatCenter
{
    public partial class RetreatSchedule : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// retrieve data and populate screen after controls (such as drop down lists) have populated themselves
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_LoadComplete(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.QueryString.Count > 0)
                {
                    ConversionUtility conversion = new ConversionUtility();
                    populateFields(conversion.stringToInt(Request.QueryString["ID"]));
                }

                if (Session["isAdmin"] != null && (bool)Session["isAdmin"] == true)
                {
                    scheduleRetreatButton.Text = "Save";
                    setControlsEditable(true);
                }
                else
                {
                    scheduleRetreatButton.Text = "Register";
                    setControlsEditable(false);
                }
            }
        }


        /// <summary>
        /// set controls with data as being editable or not
        /// </summary>
        /// <param name="isEnabled"></param>
        private void setControlsEditable(bool isEnabled)
        {
            retreatList.Enabled = isEnabled;
            staffList.Enabled = isEnabled;
            startDate.Enabled = isEnabled;
            startTime.Enabled = isEnabled;
            endDate.Enabled = isEnabled;
            endTime.Enabled = isEnabled;
            return;
        }

        /// <summary>
        /// retrieve schedule data and populate controls
        /// </summary>
        /// <param name="selectedSchedule"></param>
        private void populateFields(int selectedSchedule)
        {
            RetreatScheduleUtility retreatScheduleUtility = new RetreatScheduleUtility();
            RetreatScheduleInfo retreatScheduleInfo = retreatScheduleUtility.getRetreatScheduleByScheduleId(selectedSchedule);

            if (retreatScheduleInfo != null)
            {
                ListItem retreatItem = new ListItem(retreatScheduleInfo.retreatTitle, retreatScheduleInfo.retreatId.ToString());
                retreatList.SelectedIndex = retreatList.Items.IndexOf(retreatItem);

                ListItem directorItem = new ListItem(retreatScheduleInfo.directorName, retreatScheduleInfo.directorId.ToString());
                staffList.SelectedIndex = staffList.Items.IndexOf(directorItem);
                
                startDate.Text = retreatScheduleInfo.startTimestamp.ToShortDateString();
                startTime.Text = retreatScheduleInfo.startTimestamp.ToShortTimeString();
                endDate.Text = retreatScheduleInfo.endTimestamp.ToShortDateString();
                endTime.Text = retreatScheduleInfo.endTimestamp.ToShortTimeString();
            }
        }

        /// <summary>
        /// populate retreat list dropdown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void retreatList_OnLoad(object sender, EventArgs e)
        {
            if (retreatList.Items.Count == 0) // this fires everytime control is touched.  only need to load once
            {
                RetreatUtility retreatUtility = new RetreatUtility();
                List<RetreatInfo> retreats = retreatUtility.getAllRetreats();
                retreatList.Items.Add(new ListItem("--Select a Retreat --", "0"));

                for (int cntr = 0; cntr < retreats.Count; cntr++)
                {
                    // add all categories (categoryDesc will be displayed and categoryId will not)
                    retreatList.Items.Add(new ListItem(retreats[cntr].title, retreats[cntr].retreatId.ToString()));
                }
            }
        }

        /// <summary>
        /// populate staff dropdown list
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void staffList_OnLoad(object sender, EventArgs e)
        {
            if (staffList.Items.Count == 0) // this fires everytime control is touched.  only need to load once
            {
                UserAccountUtility userAccountUtility = new UserAccountUtility();
                List<UserAccountInfo> userAccounts = userAccountUtility.getStaffList();
                staffList.Items.Add(new ListItem("--Select a Retreat Director --", "0"));

                for (int cntr = 0; cntr < userAccounts.Count; cntr++)
                {
                      staffList.Items.Add(new ListItem(String.Format("{0} {1}", userAccounts[cntr].firstName, userAccounts[cntr].lastName), userAccounts[cntr].userId.ToString()));
                }
            }
        }

        protected void scheduleRetreatButton_Click(object sender, EventArgs e)
        {
            if (scheduleRetreatButton.Text.Equals("Save"))
            {
                SaveRetreatSchedule();
            }
            else
            {
                RegisterForRetreat();
            }
        }

        /// <summary>
        /// populate parameters and send control to retreat registration page
        /// </summary>
        private void RegisterForRetreat()
        {
            if (getUsername().Length == 0)
            {
                statusMessage.Text = "You must be logged in before registering for a retreat";
            }
            else
            {
                string redirectPage = String.Format("~/RetreatRegistration.aspx?ID={0}&Title:{1}&StartDate={2}&EndDate={3}",Request.QueryString["ID"],retreatList.SelectedItem.Text, startDate.Text, endDate.Text);
                Response.Redirect(redirectPage);
            }
        }

        /// <summary>
        /// retrieve data from screen and save to database
        /// </summary>
        private void SaveRetreatSchedule()
        {
            if (retreatList.SelectedIndex != 0)
            {
                ConversionUtility converter = new ConversionUtility();

                RetreatScheduleInfo retreatScheduleInfo = new RetreatScheduleInfo();
                String username = getUsername();
                retreatScheduleInfo.retreatId = converter.stringToInt(retreatList.SelectedItem.Value);
                retreatScheduleInfo.directorId = converter.stringToInt(staffList.SelectedItem.Value);
                retreatScheduleInfo.modifiedBy = username;
                retreatScheduleInfo.modifiedTimestamp = System.DateTime.Now;
                retreatScheduleInfo.startTimestamp = converter.stringToDateTime(startDate.Text + " " + startTime.Text);
                retreatScheduleInfo.endTimestamp = converter.stringToDateTime(endDate.Text + " " + endTime.Text);

                RetreatUtility retreatUtility = new RetreatUtility();
                RetreatScheduleUtility rsu = new RetreatScheduleUtility();
                bool success = rsu.insertRetreatSchedule(retreatScheduleInfo, username);

                if (success)
                {
                    statusMessage.Text = "Retreat successfully scheduled";
                }
                else
                {
                    statusMessage.Text = "Unable to schedule retreat";
                }
            }
            else
            {
                statusMessage.Text = "You must select a retreat";
            }
        }

        /// <summary>
        /// retrieve username from session variable, if it exists
        /// </summary>
        /// <returns></returns>
        private string getUsername()
        {
            if (Session["Username"] != null)
            {
                return Session["Username"].ToString();
            }
            else
            {
                return String.Empty;
            }
        }

        /// <summary>
        /// populate parameter and send control to view attendance for scheduled retreat
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void attendanceButton_Click(object sender, EventArgs e)
        {
            string redirectPage = String.Format("~/ViewRetreatAttendance.aspx?ID={0}", Request.QueryString["ID"]);
            Response.Redirect(redirectPage);
        }
    }
}